package com.yang.transformutils.utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.Properties;


/**
 * <p>Access数据库工具</p>
 *
 * @author By: zhangchunyang
 * Package com.yang.transformutils.utils
 * Ceate Time 2023-04-21 14:05
 */

@Slf4j
public class AccessDBUtils {

    /**
     * 加载驱动
     */
    static {
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        } catch (ClassNotFoundException e) {
            log.error(" loading  ucanaccessd driver Exception", e);
        }
    }

    /**
     * 建立连接
     *
     * @param dbUrl 数据库连接 eg： dbUrl = "jdbc:ucanaccess://D:\\yang\\test.accdb";
     * @return
     */
    public static Connection getConnection(String dbUrl) {
        try {
            return DriverManager.getConnection(dbUrl);
        } catch (Exception e) {
            log.error("get accessDB connection Exception", e);
        }
        return null;
    }

    /**
     * 建立连接
     *
     * @param dbUrl 数据库连接 eg： dbUrl = "jdbc:ucanaccess://D:\\yang\\test.accdb";
     * @return
     */
    public static Connection getConnection(String dbUrl, Properties properties) {
        try {
            return DriverManager.getConnection(dbUrl, properties);
        } catch (Exception e) {
            log.error("get accessDB connection Exception", e);
        }
        return null;
    }

    /**
     * 关闭资源
     *
     * @param connection        数据库连接
     * @param preparedStatement
     * @param resultSet
     */
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            log.error("resultSet  close SQLException", e);
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                log.error("preparedStatement  close SQLException", e);
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (Exception e) {
                        log.error("connection  close SQLException", e);
                    }
                }
            }
        }
    }


}
